<?php

namespace Biz\service\springHomeDecActivity;

use Biz\pockets\constInterface\SpringHomeDecConfig;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\LinkFormat;
use Doraemon\pockets\constInterface\Push\PushId;
use Doraemon\service\Push\PushService;
use Doraemon\tools\Log;

class ActivityPushService implements SpringHomeDecConfig
{

    public static function push(int $uid, string $date = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d', time());
        }
        if (!isset(self::PUSH_DATE_MAP[$date])) {
            return true;
        }

        $scene = self::PUSH_DATE_MAP[$date];

        return self::callPushService($scene, $uid);

    }


    public static function getScene($date){
        if (empty($date)) {
            $date = date('Y-m-d', time());
        }
        if (!isset(self::PUSH_DATE_MAP[$date])) {
            return false;
        }
        $scene = self::PUSH_DATE_MAP[$date];
        return $scene;
    }


    private static function callPushService(int $scene, $uid)
    {
        try {
            $link = Hhzurl::getDomain() . self::REMIND_LINK_URL;
            $linkArr = LinkFormat::generateLink(LinkConf::LINK_APP_FULLSCREEN, json_encode(['url' => $link]));
            $linkUrl = $linkArr['app_template'];
            $pushId = sprintf("%s%d_%d_%s", PushId::SPRING_HOME_DEC, $scene, $uid, date('Ymd'));
            $title = self::PUSH_MSG[$scene]['title'];
            $alert = self::PUSH_MSG[$scene]['alert'];
            $params = [
                'uid' => $uid,
                'title' => $title,
                'alert' => $alert,
                'param' => [
                    'link' => $linkUrl,
                    'push_id' => $pushId,
                    'image' => ''
                ]
            ];
            $res = PushService::send($params);
            if (!$res) {
                throw new \Exception(sprintf("push fail uid:%d scene:%d", $uid, $scene));
            }
            return true;
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            Log::error("push fail", ['msg' => $e->getMessage(), 'uid' => $uid, 'scene' => $scene]);
            return false;
        }
    }

}